<template>
  <div class="database-version-wrapper">
    <!-- 💭主要部分 -->
    <main class="user_main_part">
      <!-- 按钮 -->
      <section>
        <el-button type="primary" size="mini" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleCopyDatabase">复制数据库</el-button>
      </section>
      <!-- 表格 -->
      <section class="solution_table_part">
        <el-table
          :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
          :stripe="true"
          :data="tableData"
          @row-click="handleRowClick"
        >
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column align="center" width="40">
            <template v-slot="{ row }">
              <span style="cursor: pointer">
                <i class="el-icon-unlock" v-if="row.isLock === '0'"></i>
                <i class="el-icon-lock" v-if="row.isLock === '1'"></i>
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据库版本" prop="databaseVersion"></el-table-column>
          <el-table-column align="center" label="方案版本" prop="schemeNum">
            <template slot-scope="scope">
              <span>{{ scope.row.schemeNum }}</span>
              <el-button
                size="mini"
                circle
                icon="el-icon-edit"
                style="margin-left: 6px"
                @click.stop="handleEditSchemeNum(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="versionNum">
            <template slot-scope="scope">
              <div :class="scope.row.ecrfStatus === '1' ? 'status-box active-background-color' : 'status-box'">C</div>
              <div :class="scope.row.ecStatus === '1' ? 'status-box active-background-color' : 'status-box'">E</div>
              <div :class="scope.row.serverStatus === '1' ? 'status-box active-background-color' : 'status-box'">D</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="ecBatchNum">
            <template slot="header" slot-scope="scope">
              {{ scope.row }}
              <div style="display: flex; justify-content: center">
                <span>DEV</span>
                <el-tooltip content="进入测试环境" placement="top" effect="light" v-if="isShowGoDev">
                  <img
                    style="width: 24px; cursor: pointer"
                    src="@/assets/img/computer.png"
                    alt=""
                    @click="gotoUserEnd()"
                  />
                </el-tooltip>
              </div>
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.devStatus === '1' ? '已发布' : '未发布' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="PRO已发布版本" prop="ecBatchTime">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.proVerNums && scope.row.proVerNums.length > 0">{{
                scope.row.proVerNums && scope.row.proVerNums.length > 0 ? scope.row.proVerNums[0].databaseNum : ''
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="opt" align="center" width="240px" label="操作">
            <template slot-scope="scope" v-if="scope.row.id === firstRowId">
              <el-button
                icon="el-icon-position"
                size="mini"
                circle
                @click.stop="handlePublishVersion(scope.row)"
                title="发布"
              ></el-button>
              <el-button
                icon="el-icon-refresh"
                size="mini"
                circle
                @click.stop="handleCover(scope.row)"
                title="DEV版本覆盖建库版本"
              ></el-button>
              <el-button
                icon="el-icon-document-copy"
                size="mini"
                circle
                @click.stop="e => handleClone(e, scope.row)"
                title="克隆"
              ></el-button>
              <el-button
                icon="el-icon-delete"
                size="mini"
                circle
                @click.stop="e => btnDelete(scope.row)"
                title="删除"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </main>
    <clone
      :cloneVisible="cloneVisible"
      @handleCloneCancel="handleCloneCancel"
      :projectId="projectId"
      :cloneData="cloneData"
    ></clone>
    <publish
      :publishVisible="publishVisible"
      @handlePublishCancel="handlePublishCancel"
      :projectId="projectId"
      :publishData="publishData"
    ></publish>
    <copy
      :copyVisible="copyVisible"
      @handleCopyDatabaseCancel="handleCopyDatabaseCancel"
      :projectId="projectId"
      :sourceProjectList="sourceProjectList"
      :solutionList="solutionList"
    ></copy>
    <editScheme
      :editSchemeVisible="editSchemeVisible"
      :solutionList="solutionList"
      @handleEditSchemeCancel="handleEditSchemeCancel"
      :editSchemeData="editSchemeData"
    ></editScheme>
    <!-- 进入测试环境弹窗 -->
    <!-- 测试项目选择角色和中心的弹窗 -->
    <el-dialog :visible="entryVisible" title="进入测试项目" width="500px" @close="handleCancel">
      <el-form ref="formEntryRef" label-width="120px" :model="formEntryData" :rules="formEntryRules">
        <el-form-item label="选择角色：" prop="roleValue">
          <el-select style="width: 80%" size="mini" v-model="formEntryData.roleValue" @change="handleRoleChange">
            <el-option v-for="item in roleOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="coreSelectVis" label="选择中心：" prop="coreValue">
          <el-select
            style="width: 80%; margin-right: 4px"
            size="mini"
            collapse-tags
            v-model="formEntryData.coreValue"
            multiple
          >
            <el-option
              v-for="item in coreOptions"
              :key="item.coreId"
              :value="item.coreId"
              :label="item.coreName"
            ></el-option>
          </el-select>
          <el-button size="mini" type="primary" @click="handleSelectAll()">全选</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleConfirm()" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import routes from '@/router/users-manage'
import clone from './components/clone.vue'
import publish from './components/publish.vue'
import copy from './components/copy.vue'
import editScheme from './components/edit-scheme.vue'
import moduleRouter from '@/router/module-router.js'

export default {
  components: {
    clone,
    publish,
    copy,
    editScheme,
  },

  data() {
    return {
      tableData: [],
      formData: {
        schemeId: '',
        versionNum: '',
        versionTime: '',
        ecBatchNum: '',
        ecBatchTime: '',
      },
      formRules: {
        sourceProject: [{ required: true, message: '请输入', trigger: 'blur' }],
        sourceProjectDatabaseVersion: [{ required: true, message: '请输入', trigger: 'blur' }],
        databaseVersion: [{ required: true, message: '请输入', trigger: 'blur' }],
        schemeVersion: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      publishVisible: false,
      cloneVisible: false,
      coverVisible: false,
      projectId: '',
      copyVisible: false,
      sourceProjectList: [],
      publishData: {},
      cloneData: {},
      solutionList: [],
      editSchemeVisible: false,
      editSchemeData: {},
      firstRowId: '',
      // 用户id
      userId: '',
      formEntryData: {
        roleValue: '',
        coreValue: [],
      },
      roleOptions: [],
      coreOptions: [],
      projectDatabaseId: '',
      entryVisible: false,
      coreSelectVis: true,
      formEntryRules: {
        roleValue: [{ required: true, message: '请填写', trigger: 'blur' }],
        coreValue: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      standardRoleArr: ['DM', 'ReadOnlyAll', 'PM', 'DBB', 'DBBAdmin'],
      isShowGoDev: false,
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id')
    this.userId = JSON.parse(localStorage.getItem('user-info')).id
    this.getDatabaseVersionList()
    this.getProjectDatabaseId()
  },

  methods: {
    ...mapActions('solutionVersion', [
      'qryProjectDatabaseVersion',
      'rollbackProjectDatabaseVersion',
      'coverDatabaseVersion',
      'qrySolutionListAPI',
      'deleteDatabaseVersion',
      'getProjectRoleListByUserAPI',
      'getProjectDatabaseIdAPI',
    ]),
    ...mapActions('projectList', ['qryProjectListNoPage', 'getListByRoleAPI']),
    ...mapActions('roleManage', ['getRoleDataAPI']),
    ...mapActions('subjectInformation', ['getUpdateSubjectInfo']),
    ...mapActions('userData', ['getListMenus', 'getPermissionInfo']),

    // 根据项目id获取不同环境ProjectDatabaseId
    async getProjectDatabaseId() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.getProjectDatabaseIdAPI({ params })
      if (res.code === 200 && res.data.length) {
        const obj = res.data.find(item => item.projectType === 2)
        this.projectDatabaseId = obj.id
      }
    },

    // 选择角色
    handleRoleChange(val) {
      const obj = this.roleOptions.find(item => item.id === val)
      const roleCode = obj.code
      if (this.standardRoleArr.includes(roleCode)) {
        this.coreSelectVis = false
        const arr = []
        this.coreOptions.forEach(item => {
          arr.push(item.coreId)
        })
        this.formEntryData.coreValue = arr
      } else {
        this.coreSelectVis = true
        this.formEntryData.coreValue = []
      }
    },

    // 获取项目中角色
    async getProjectRoleData() {
      const params = {
        pageSize: 1000,
        pageNo: 1,
        projectId: this.projectId,
      }
      const res = await this.getRoleDataAPI({ params })
      if (res.code === 200) {
        res.data.records.forEach(item => {
          item.name = item.name + '(' + item.code + ')'
        })
        this.roleOptions = res.data.records
        localStorage.setItem('project-roles', JSON.stringify(res.data.records))
      }
    },

    // 获取项目中中心
    async getProjectCenterData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getUpdateSubjectInfo({ params })
      if (res.code === 200) {
        this.coreOptions = res.data
      }
    },

    // 全选
    handleSelectAll() {
      this.coreOptions.forEach(item => {
        if (!this.formEntryData.coreValue.includes(item.coreId)) {
          this.formEntryData.coreValue.push(item.coreId)
        }
      })
    },

    // 获取角色对应的项目菜单列表
    async getRoleHaveMenuList(roleId) {
      const params = {
        roleId,
      }
      const res = await this.getListByRoleAPI({ params })
      localStorage.setItem('project-menu-permission', JSON.stringify(res.data))
    },

    // 弹窗确认
    async handleConfirm() {
      await this.$refs.formEntryRef.validate()
      this.getRoleHaveMenuList(this.formEntryData.roleValue)
      localStorage.setItem('coreIds', JSON.stringify(this.formEntryData.coreValue))
      const selectedCoreList = []
      this.coreOptions.map((cItem, cIndex) => {
        if (this.formEntryData.coreValue.includes(cItem.coreId)) {
          selectedCoreList.push(cItem)
        }
      })
      localStorage.setItem('coreOfficialOptions', JSON.stringify(selectedCoreList))
      this.$store.commit('layoutHeader/setRoleId', this.formEntryData.roleValue)
      localStorage.setItem('projectRoleCode', this.formEntryData.roleCode)
      // 设置角色名
      let roleName = ''
      this.roleOptions.forEach(item => {
        if (item.id === this.formEntryData.roleValue) {
          roleName = item.name
        }
      })
      this.$store.commit('layoutHeader/setRoleName', roleName)
      this.$store.commit('layoutHeader/setRoleOptions', this.roleOptions)

      // 权限判断同时设置菜单权限
      this.getUserMenus(localStorage.getItem('sys-project-id'), this.formEntryData.roleValue)
      this.$refs.formEntryRef.resetFields()
      this.entryVisible = false
    },

    // 进入项目重新加载权限菜单
    getUserMenus(projectId, roleId) {
      const params = {
        projectId,
        roleId,
      }
      this.getListMenus({ params }).then(res => {
        const { code, data } = res
        if (code === 200 && data.length > 0) {
          if (data.length === 1 && data[0].children.length === 0) {
            this.$message.error('暂无进入项目权限，请联系管理员~')
            return ''
          }
          localStorage.setItem('system-menu-list', JSON.stringify(res.data))
          this.getUserPermissions(projectId, roleId)
          this.$router.push({
            path: moduleRouter.subjectInformationSummary.path,
            name: moduleRouter.subjectInformationSummary.name,
            query: {
              id: this.projectId,
            },
          })
        } else {
          console.log('获取项目菜单、按钮权限异常')
        }
      })
    },

    // 进入项目重新查询用户权限菜单
    getUserPermissions(projectId, roleId) {
      const params = {
        projectId,
        roleId,
      }
      this.getPermissionInfo({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          localStorage.setItem('user-permissions', JSON.stringify(data.permissions))
        }
      })
    },

    // 弹窗取消
    handleCancel() {
      this.$refs.formEntryRef.resetFields()
      this.entryVisible = false
    },

    async gotoUserEnd() {
      // 获取项目角色下拉项
      await this.getProjectRoleData()
      // 获取项目中心下拉项
      await this.getProjectCenterData()
      this.entryVisible = true
      localStorage.setItem('environment', 1)
      // 菜单
      localStorage.setItem('showMenuType', 5)
      // 储存项目数据库id
      localStorage.setItem('project-database-Id', this.projectDatabaseId) // projectDatabaseId
    },

    // 获取数据库版本列表
    getDatabaseVersionList() {
      const params = {
        projectId: this.projectId,
      }
      this.qryProjectDatabaseVersion({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          this.tableData = data
          const obj = this.tableData.find(item => item.devStatus === '1')
          if (obj) {
            this.isShowGoDev = true
          } else {
            this.isShowGoDev = false
          }

          if (data.length > 0) {
            this.firstRowId = data[0].id
          } else {
            this.firstRowId = ''
          }
        }
      })
    },

    // 修改数据库方版本
    handleEditSchemeNum(row) {
      this.editSchemeData = row
      this.editSchemeVisible = true
      this.getSolutionListAPI()
    },

    // 修改方案版本取消
    handleEditSchemeCancel(type) {
      this.editSchemeVisible = false
      if (type === 'refresh') {
        this.getDatabaseVersionList()
      }
    },

    // 刷新
    handleRefresh() {
      this.getDatabaseVersionList()
    },

    // 发布
    handlePublishVersion(record) {
      this.publishData = record
      this.publishVisible = true
    },

    // 关闭发布弹框
    handlePublishCancel(type) {
      this.publishVisible = false
      if (type === 'refresh') {
        this.getDatabaseVersionList()
      }
    },

    // 克隆
    handleClone(e, record) {
      e.stopPropagation()
      this.cloneData = record
      this.cloneVisible = true
    },

    // 克隆弹框取消
    handleCloneCancel(type) {
      this.cloneVisible = false
      if (type === 'refresh') {
        this.getDatabaseVersionList()
      }
    },

    // 测试点击某一行
    handleRowClick(record) {
      localStorage.setItem('showMenuType', 4)
      const isLock = record.isLock
      const databaseInfo = {
        databaseId: record.id,
        databaseVersion: '0',
        isLock,
      }
      localStorage.setItem('sys-database-info', JSON.stringify(databaseInfo))
      this.$router.push({
        path: routes.eCRFDesign.path,
        name: routes.eCRFDesign.name,
        query: {
          id: record.id,
        },
      })
      setTimeout(() => {
        location.reload()
      }, 100)
    },

    handleClock() {},

    // 复制数库
    handleCopyDatabase() {
      this.$message.error('功能正在完善中，敬请期待~')
      // this.copyVisible = true
      // this.getSourceProjectList()
      // this.getSolutionListAPI()
    },

    // 查询方案列表
    getSolutionListAPI() {
      const params = {
        projectId: this.projectId,
      }
      this.qrySolutionListAPI({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.solutionList = data || []
        }
      })
    },

    // 关闭复制数库弹框
    handleCopyDatabaseCancel(type) {
      this.copyVisible = false
      if (type === 'refresh') {
        this.getDatabaseVersionList()
      }
    },

    // 查询源项目列表
    getSourceProjectList() {
      this.qryProjectListNoPage().then(res => {
        const { data, code } = res
        if (code === 200) {
          this.sourceProjectList = data || []
        }
      })
    },

    // 点击删除
    btnDelete(row) {
      this.$confirm('确认删除该条数据？', '提示', {
        type: 'warning',
      }).then(async res => {
        const params = {
          id: row.id,
        }
        const result = await this.deleteDatabaseVersion({ params })
        if (result.code === 200) {
          this.$message.success('删除成功')
          this.getDatabaseVersionList()
        }
      })
    },

    // 覆盖
    handleCover(row) {
      this.$confirm('确认用DEV版本覆盖建库版本吗?', '提示', {
        type: 'warning',
      }).then(async res => {
        const params = {
          projectId: this.projectId,
          databaseVersion: row.id,
          fromProjectType: '2',
          toDatabaseNum: '0',
        }
        const result = await this.rollbackProjectDatabaseVersion({ params })
        if (result.code === 200) {
          this.$message.success('操作成功!')
          this.getDatabaseVersionList()
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
